package com.health.activity.settings;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.R;
import com.health.adapter.UPDataMenuGridAdapter;
import com.health.db.FDbManager;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tools.DownLoadTools;
import com.health.tools.GetPost;
import com.health.tools.GetPostJTYS;
import com.health.tools.GlobalConts;
import com.health.tools.GlobalContsJTYS;
import com.health.tools.ResultTextDialog;
import com.health.tools.SPUtil;
import com.health.tools.WebService;
import com.health.viewscontrols.HomeDataDownloadActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * 同步数据
 * 
 *
 */
public class DataSynchronizationMainActivity extends NovaActivity implements OnClickListener {
	private static final int MAX_PROGRESS = 100;
	private static final int PRO = 10;
	private int progress = 0;
	private ProgressDialog mProgressDialog;
	private ResultTextDialog resultDialog;
	private GridView gd_menu;
	private TextView title;
	private ImageView img_photo;
	private TextView tv_name;
	private UPDataMenuGridAdapter menuAdapter;
	private Button btn_back;
	private Button btn_up;
	private String str_xzq = "";
	private FDbManager fdbmanger = null;
	List<ARCHIVE_BASEINFO> isUpdate = new ArrayList<>();
	private int sumSize;
	private int successCount;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// StrictMode.ThreadPolicy policy=new
		// StrictMode.ThreadPolicy.Builder().permitAll().build();
		// StrictMode.setThreadPolicy(policy);
		setContentView(R.layout.jkjy_main_content);
		findViews();
		setListeners();

	}

	@Override
	public void findViews() {
		gd_menu = (GridView) findViewById(R.id.gd_menu);
		title = (TextView) findViewById(R.id.title);
		title.setText("同步机构人员");

		img_photo = (ImageView) findViewById(R.id.img_photo);
		img_photo.setImageResource(R.drawable.settings_data);
		tv_name = (TextView) findViewById(R.id.tv_name);
		tv_name.setText("同步机构人员");

		menuAdapter = new UPDataMenuGridAdapter(this, GlobalContsJTYS.MENU_SYNCHRONIZATION);
		gd_menu.setAdapter(menuAdapter);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_up = (Button) findViewById(R.id.btn_up);
		btn_up.setVisibility(View.GONE);

		str_xzq = SPUtil.getstr_xzq(DataSynchronizationMainActivity.this);
		fdbmanger = NovaApplication.fdbmanger;
		if (resultDialog == null) {
			resultDialog = new ResultTextDialog(DataSynchronizationMainActivity.this);
		}
	}

	/**
	 * 更新机构人员
	 */
	public void updateJGRY() {
		String fileURl = GlobalConts.getUrlPost() + GetPost.URL_DBSYNC + "?orgDistrictId=" + str_xzq;
		DownLoadTools downLoad = new DownLoadTools(DataSynchronizationMainActivity.this);
		downLoad.downloadFile(fileURl, NovaApplication.dbPath);
	}

	@Override
	public void setListeners() {
		btn_back.setOnClickListener(this);
		// 菜单选项
		gd_menu.setOnItemClickListener(new OnItemClickListener() {

			@SuppressLint("HandlerLeak")
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!GlobalConts.isNetworkAvailable(DataSynchronizationMainActivity.this)) {
					showTextDialog("请先检查网络");
					return;
				}
				if (position == 0) {
//					// 实现同步数据
//					if (GlobalConts.isNetworkAvailable(DataSynchronizationMainActivity.this)) {
//						isUpdate = fdbmanger.findAllByWhere(ARCHIVE_BASEINFO.class, " IS_UPDATE= 'Y'");
//						if (isUpdate.size() == 0) {
//							// 选择是否上传
//							new AlertDialog.Builder(DataSynchronizationMainActivity.this).setTitle("是否更新行政机构人员?")
//									.setMessage("更新机构人员本地数据将会被清空，请谨慎操作，是否更新？")
//									.setPositiveButton("是", new DialogInterface.OnClickListener() {
//
//										@Override
//										public void onClick(DialogInterface dialog, int which) {
//											updateJGRY();
//										}
//
//									}).setNegativeButton("否", new DialogInterface.OnClickListener() {
//										// 同步数据
//										@Override
//										public void onClick(DialogInterface dialog, int which) {
//
//										}
//
//									}).show();
//
//						} else {
//							// 选择是否上传
//							new AlertDialog.Builder(DataSynchronizationMainActivity.this).setTitle("操作提示(是否上传?)")
//									.setMessage("1. 您有 " + isUpdate.size() + "条数据未上传 ,请先进行 数据上传 后再进行该操作 !\n"
//											+ "2. 更新机构人员后数据将会被清空,请谨慎操作!")
//									.setPositiveButton("是", new DialogInterface.OnClickListener() {
//
//										@Override
//										public void onClick(DialogInterface dialog, int which) {
//
//											// Intent mIntent = new Intent();
//											// mIntent.putExtra("page", "3");
//											// setResult(20, mIntent);
//											// finish();
//											Intent intent = new Intent(DataSynchronizationMainActivity.this,
//													DataDownLoadMainActivity.class);
//											startActivity(intent);
//											finish();
//										}
//
//									}).setNegativeButton("否", new DialogInterface.OnClickListener() {
//										// 同步数据
//										@Override
//										public void onClick(DialogInterface dialog, int which) {
//											updateJGRY();
//										}
//
//									}).show();
//						}
//
//					} else {
//						Toast.makeText(DataSynchronizationMainActivity.this, "请检查网络连接", 0).show();
//					}
					Intent intent = new Intent(DataSynchronizationMainActivity.this, HomeDataDownloadActivity.class);
					intent.putExtra("setting", "setting");
					startActivity(intent);
				} 
				else if (position == 1)
					if (GlobalConts.isNetworkAvailable(DataSynchronizationMainActivity.this)) {
						new AlertDialog.Builder(DataSynchronizationMainActivity.this).setTitle("提示")
								.setMessage("是否要同步本机构用户？")
								.setPositiveButton("是", new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										initProgressDialog();
										sumSize = 0;
										successCount = 0;
										showProgressDialog("正在获取数据...");
										Handler handler = new Handler() {
											@Override
											public void handleMessage(Message msg) {
												super.handleMessage(msg);
												System.out.println("webservice");
												try {
													new WebService(mContext) {
														@Override
														public void start(String message) {
															super.start(message);
															System.out.println("test111" + message);

														}

														@Override
														public void onSynchronize(String message, int syncCount,
																				  int dataSize) {
															super.onSynchronize(message, syncCount, dataSize);
															sumSize = dataSize;
															successCount = syncCount;
															cancelProgressDialog();
															runOnUiThread(new Runnable() {
																@Override
																public void run() {
																	if (mProgressDialog != null
																			&& !mProgressDialog.isShowing()) {
																		mProgressDialog.show();
																	}
																}
															});
															mProgressDialog.setMax(dataSize);
															mProgressDialog.setProgress(syncCount);
														}

														@Override
														public void complete(String message) {
															super.complete(message);
															cancelProgressDialog();
															if (mProgressDialog != null) {
																mProgressDialog.dismiss();
																mProgressDialog.cancel();
															}
															runOnUiThread(new Runnable() {

																@Override
																public void run() {
																	resultDialog.setText("下载数据总共" + sumSize
																			+ "条,保存成功" + successCount + "条,保存失败"
																			+ (sumSize - successCount) + "条");
																	resultDialog.showCancleLong();
																}
															});
														}

														public void onError(String message) {
															System.out.println("同步本机构人员失败");
															cancelProgressDialog();
															if (mProgressDialog != null) {
																mProgressDialog.dismiss();
																mProgressDialog.cancel();
															}
															runOnUiThread(new Runnable() {

																@Override
																public void run() {
																	resultDialog.setText("下载数据总共" + sumSize
																			+ "条,保存成功" + successCount + "条,保存失败"
																			+ (sumSize - successCount) + "条");
																	resultDialog.showCancleLong();

																}
															});

														};
													}.synchrodata(SPUtil.getStr_jdrno(DataSynchronizationMainActivity.this));
												} catch (Exception e) {
													e.printStackTrace();
													if (mProgressDialog != null) {
														mProgressDialog.dismiss();
														mProgressDialog.cancel();
													}
													runOnUiThread(new Runnable() {
														@Override
														public void run() {
															resultDialog.setText("数据同步失败");
															resultDialog.showCancleLong();
														}
													});
												}
											}
										};
										handler.sendMessage(new Message());
									}

								}).setNegativeButton("否", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {

							}

						}).show();
						//
					} else {
						Toast.makeText(DataSynchronizationMainActivity.this, "数据同步失败", Toast.LENGTH_SHORT).show();
					}


			}

			private void initProgressDialog() {
				mProgressDialog = new ProgressDialog(DataSynchronizationMainActivity.this);
				// progressDialog.setIcon(R.drawable.ic_launcher);
				mProgressDialog.setTitle("正在同步数据");
				mProgressDialog.setMessage("请稍候...");
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 璁剧疆杩涘害鏉″璇濇//鏍峰紡锛堟按骞筹紝鏃嬭浆锛�
			
			}

		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			finish();
			break;

		default:
			break;
		}

	}

	private void showSynDialog(final Context context) {
		LayoutInflater inflater = LayoutInflater.from(this);
		final View textEntryView = inflater.inflate(R.layout.syn_dialog, null);
		final EditText ed_xzbh = (EditText) textEntryView.findViewById(R.id.ed_xzbh);
		ed_xzbh.setText(SPUtil.getstr_xzq(DataSynchronizationMainActivity.this));
		final EditText ed_pwd = (EditText) textEntryView.findViewById(R.id.ed_pwd);
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setCancelable(false);
		builder.setView(textEntryView);
		builder.setPositiveButton("同步", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				String str_xzbh = ed_xzbh.getText().toString();
				if (TextUtils.isEmpty(str_xzbh) || str_xzbh.length() != 6) {
					showTextDialog("请输入正确的行政编号");
					return;
				}
				String str_pwd = ed_pwd.getText().toString();
				if (str_pwd.equals("nova8888")) {
					String fileURl = GlobalConts.getUrlPost() + GetPostJTYS.URL_DBSYNC + "?orgDistrictId=" + str_xzbh;
					Log.w("eeeeeeeeeeeeee", fileURl);
					if (!TextUtils.isEmpty(fileURl)) {
						SPUtil.setstr_xzq(DataSynchronizationMainActivity.this, str_xzbh);
						DownLoadTools downLoad = new DownLoadTools(context);
						downLoad.downloadFile(fileURl, NovaApplication.dbPath);
					}
				} else {
					showTextDialog("密码有误，请重新输入");
				}

			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	}

}

// else if (position == 1) {
// // 选择是否更改
// new
// AlertDialog.Builder(DataSynchronizationMainActivity.this).setTitle("是否更改行政区？")
// .setMessage("更改更新行政区之后，本地数据会被备份，将会变为空数据，是否更改？")
// .setPositiveButton("是", new DialogInterface.OnClickListener()
// {
//
// @Override
// public void onClick(DialogInterface dialog, int which) {
// // 实现设置行政区
// showSynDialog(DataSynchronizationMainActivity.this);
// }
//
// }).setNegativeButton("否", new
// DialogInterface.OnClickListener() {
// // 同步数据
// @Override
// public void onClick(DialogInterface dialog, int which) {
//
// }
//
// }).show();
// }
//